/*
XCommander Extension
http://www.xcommander.ch/
*/

window.addEventListener('load', function() {
	xcommander.lib.messaging.server.addMessageListener('browser', function(message) {
		switch(message.data.method) {
			case 'createTab':
				var url = message.data.url;
				if(url.indexOf(xcommander.lib.getExtensionScheme()) == 0) {
					url = xcommander.lib.browser.getExtensionUrl(url.replace(xcommander.lib.getExtensionScheme(), ''));
				}
				xcommander.lib.browser.createTab(url);
				break;
			case 'navigateTo':
				var url = message.data.url;
				if(url.indexOf(xcommander.lib.getExtensionScheme()) == 0) {
					url = xcommander.lib.browser.getExtensionUrl(url.replace(xcommander.lib.getExtensionScheme(), ''));
				}
				xcommander.lib.browser.navigateTo(url);
				break;
			case 'getExtensionUrl':
				var extensionPath = xcommander.lib.browser.getExtensionUrl(message.data.relativePath);
				message.sendResponse(extensionPath);
				break;
		}
	});

	xcommander.lib.messaging.server.addMessageListener('storage', function(message) {
		switch(message.data.method) {
			case 'getItem':
				data = xcommander.lib.storage.getItem(message.data.key);
				break;
			case 'getJSONItem':
				data = xcommander.lib.storage.getJSONItem(message.data.key);
				break;
			case 'setItem':
				data = xcommander.lib.storage.setItem(message.data.key, message.data.value);
				break;
			case 'setJSONItem':
				data = xcommander.lib.storage.setJSONItem(message.data.key, message.data.value);
				break;
			case 'removeItem':
				data = xcommander.lib.storage.removeItem(message.data.key);
				break;
			case 'clear':
				data = xcommander.lib.storage.clear();
				break;
			case 'getKeys':
				data = xcommander.lib.storage.getKeys();
				break;
		}
		message.sendResponse(data);
	});

	xcommander.lib.messaging.server.addMessageListener('xhr', function(message) {
		xcommander.lib.xhr.send(message.data, function(data) {
			message.sendResponse(data);
		})
	});

	xcommander.lib.init();
}, false);
